<template>
  <el-dialog
    :title="formData.id ? '编辑数据源' : '新建数据源'"
    v-model="dialogVisible"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <el-form-item label="数据源名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入数据源名称" />
      </el-form-item>

      <el-form-item label="数据源类型" prop="type">
        <el-select
          v-model="formData.type"
          placeholder="请选择数据源类型"
          style="width: 100%"
        >
          <el-option
            v-for="type in Object.values(DataSourceType)"
            :key="type"
            :label="type"
            :value="type"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="主机地址" prop="host">
        <el-input v-model="formData.host" placeholder="请输入主机地址" />
      </el-form-item>

      <el-form-item label="端口" prop="port">
        <el-input-number
          v-model="formData.port"
          :min="1"
          :max="65535"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>

      <el-form-item label="数据库名" prop="database">
        <el-input v-model="formData.database" placeholder="请输入数据库名" />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :loading="testing"
          @click="handleTest"
          style="width: 120px"
        >
          测试连接
        </el-button>
        <span
          v-if="testResult"
          :class="['test-result', testResult.success ? 'success' : 'error']"
        >
          {{ testResult.message }}
        </span>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import type { DataSource } from "@/types/dataSource";
import { DataSourceType, DataSourceStatus } from "@/types/dataSource";
import { testDataSourceConnection } from "@/api/dataSource";

const props = defineProps<{
  visible: boolean;
  editData?: DataSource;
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "submit", data: DataSource): void;
}>();

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit("update:visible", val),
});

const formRef = ref<FormInstance>();
const submitting = ref(false);
const testing = ref(false);
const testResult = ref<{ success: boolean; message: string } | null>(null);

const defaultForm: Omit<DataSource, "id" | "status"> = {
  name: "",
  type: DataSourceType.MySQL,
  host: "",
  port: 3306,
  username: "",
  password: "",
  database: "",
};

const formData = reactive<DataSource>({
  ...defaultForm,
  status: DataSourceStatus.Disconnected,
});

const rules: FormRules = {
  name: [{ required: true, message: "请输入数据源名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择数据源类型", trigger: "change" }],
  host: [{ required: true, message: "请输入主机地址", trigger: "blur" }],
  port: [{ required: true, message: "请输入端口号", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  database: [{ required: true, message: "请输入数据库名", trigger: "blur" }],
};

watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      Object.assign(formData, newVal);
    } else {
      Object.assign(formData, {
        ...defaultForm,
        status: DataSourceStatus.Disconnected,
      });
    }
  },
  { immediate: true }
);

const handleClose = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
  Object.assign(formData, {
    ...defaultForm,
    status: DataSourceStatus.Disconnected,
  });
  testResult.value = null;
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid) => {
    if (valid) {
      submitting.value = true;
      try {
        emit("submit", { ...formData });
        handleClose();
      } finally {
        submitting.value = false;
      }
    }
  });
};

const handleTest = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
  } catch (error) {
    return;
  }

  testing.value = true;
  testResult.value = null;

  try {
    if (formData.id) {
      const result = await testDataSourceConnection(formData.id);
      testResult.value = result;
      if (result.success) {
        formData.status = DataSourceStatus.Connected;
      } else {
        formData.status = DataSourceStatus.Error;
      }
    } else {
      await new Promise((resolve) => setTimeout(resolve, 1000));
      testResult.value = {
        success: true,
        message: "连接测试成功",
      };
      formData.status = DataSourceStatus.Connected;
    }
  } catch (error) {
    testResult.value = {
      success: false,
      message: "连接测试失败",
    };
    formData.status = DataSourceStatus.Error;
  } finally {
    testing.value = false;
  }
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.test-result {
  margin-left: 12px;
  font-size: 14px;
}

.test-result.success {
  color: var(--el-color-success);
}

.test-result.error {
  color: var(--el-color-danger);
}
</style> 